package com.yearner.reviewplan.user;

import com.yearner.reviewplan.user.commands.ChangePasswordCommand;
import com.yearner.reviewplan.user.commands.RegisterUserAccountCommand;
import com.yearner.reviewplan.user.exceptions.AccountNameRedoException;
import com.yearner.reviewplan.user.model.User;
import com.yearner.reviewplan.user.model.UserFactory;
import org.springframework.stereotype.Service;

/**
 * User "写"模型的门面
 * 作为【领域模型】的调用方,本身不应该包含业务逻辑,业务逻辑交给聚合根
 * 不包含查询，查询请找 Representation(基于数据模型)
 * @author pengyg
 * @since 2019/10/12
 */
@Service
public class UserApplicationService {
    private final UserRepository userRepository;
    private final UserFactory userFactory;

    public UserApplicationService(UserRepository userRepository,UserFactory userFactory) {
        this.userRepository = userRepository;
        this.userFactory = userFactory;
    }


    public User register(RegisterUserAccountCommand command) {
        if (userRepository.exist(command.getAccountName())) {
            throw new AccountNameRedoException();
        }
        User newUser = userFactory.register(command);
        userRepository.save(newUser);
        return newUser;
    }

    public void changeCycle(Double[] cycle,String userId) {
        User user = userRepository.byId(userId);
        user.changeCycle(cycle);
        userRepository.save(user);
    }


    User changePassword(ChangePasswordCommand command) {
        User user = userRepository.byId(command.getUserId());
        userFactory.validPassword(command.getNewPassword());
        user.changePassword(command);
        userRepository.save(user);
        return user;
    }
}
